#ifndef __NorFlash_SPI_C
#define __NorFlash_SPI_C

#include "NorFlashSPI.h"

void SPI_NorFlash_init(){
	  GPIO_Config_T  configStruct;
	  SPI_Config_T spiConfig;
	
	  RCM_EnableAPB2PeriphClock(NorFalsh_SPI_PinRCM);
	  RCM_EnableAPB2PeriphClock(RCM_APB2_PERIPH_AFIO);
	
	  #ifdef NorFalsh_SPI_CS_RCM
    RCM_EnableAPB2PeriphClock(NorFalsh_SPI_CS_RCM);
	  #endif
	  	
	  GPIO_ConfigPinRemap(GPIO_REMAP_SWJ_JTAGDISABLE);
	  
	  // SPI引脚初始化：
	  // SCLK MOSI
	  configStruct.pin = NorFalsh_SPI_SCLK_PinId | NorFalsh_SPI_MOSI_PinId;           
	  configStruct.mode = GPIO_MODE_AF_PP;  
    configStruct.speed = 	GPIO_SPEED_50MHz;
	  GPIO_Config(NorFalsh_SPI_PinPort, &configStruct);       
	  // MISO
	  configStruct.pin = NorFalsh_SPI_MISO_PinId;           
	  configStruct.mode = GPIO_MODE_IN_FLOATING;          
	  GPIO_Config(NorFalsh_SPI_PinPort, &configStruct);
	
		// CS
		configStruct.pin = NorFalsh_SPI_CS_PinId;           
	  configStruct.mode = GPIO_MODE_OUT_PP;  
    #ifdef NorFalsh_SPI_CS_PinPort
    GPIO_Config(NorFalsh_SPI_CS_PinPort, &configStruct);	
	  #else
	  GPIO_Config(NorFalsh_SPI_PinPort, &configStruct);	
	  #endif 	
    // CS初始化为高电平
		NorFalsh_SPI_CS_set();		
	  		  
	  // SPI功能初始化：    
    RCM_EnableAPB1PeriphClock(NorFalsh_SPI_RCM);
	  SPI_ConfigStructInit(&spiConfig);
    // 字节长度
    spiConfig.length = SPI_DATA_LENGTH_8B;
    // 波特率分频：
    spiConfig.baudrateDiv = SPI_BAUDRATE_DIV_4;
    // 两线全双工
    spiConfig.direction = SPI_DIRECTION_2LINES_FULLDUPLEX;
    // 高位先行:
    spiConfig.firstBit = SPI_FIRSTBIT_MSB;
    // 主设备模式：
    spiConfig.mode     = SPI_MODE_MASTER;
    // SPI时钟极性CPOL = 1：闲时高电平。模式3
    spiConfig.polarity = SPI_CLKPOL_HIGH;
    // SPI片选模式选择：软件片选 or 硬件片选
    spiConfig.nss = SPI_NSS_SOFT;
    // SPI时钟相位CPHA = 1 = 第1个沿是写：采集数据是第2边沿。模式3
    spiConfig.phase = SPI_CLKPHA_2EDGE;
		// CRC校验设置
		#ifndef AT32F403AVGT7
		spiConfig.crcPolynomial = 7;
		#endif
    // SPI config： 
    SPI_Config(NorFalsh_SPI_id, &spiConfig);		
    // 使能SPI；
    SPI_Enable(NorFalsh_SPI_id);		
		
		#ifdef SYS_DEBUG
		printf(" SPI_NorFlash_init finish   \r\n");
		#endif
		
}

// SPI发送
uint8_t SPI_NorFlash_SendRead_Byte(uint8_t data){
	  uint8_t timeout = 252;
	  while (SPI_I2S_ReadStatusFlag(NorFalsh_SPI_id, SPI_FLAG_TXBE) == RESET && timeout--){
			 
		}
    SPI_I2S_TxData(NorFalsh_SPI_id, data);		
		timeout = 252;
	  while (SPI_I2S_ReadStatusFlag(NorFalsh_SPI_id, SPI_FLAG_RXBNE) == RESET && timeout--){
			  
		}
    return (uint8_t)SPI_I2S_RxData(NorFalsh_SPI_id);
}


#endif

